import router from '@/router'
import axios, { AxiosRequestConfig } from 'axios'
import Cookies from 'js-cookie'
import { clearLoginInfo } from '@/api/user/index'
import { ElMessage } from 'element-plus'

const http = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

/**
 * 请求拦截
 */
http.interceptors.request.use((config: AxiosRequestConfig) => {
  Object.assign(config.headers, {
    'token': Cookies.get('token')
  })
  return config
}, error => {
  console.log(error) // for debug
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  if (response.data && response.data.code === 401) { // 401, token失效
    clearLoginInfo()
    router.push({ name: 'login' })
  } else if (response.data.code >= 500) {
    ElMessage.error(response.data.msg)
  }
  return response
}, error => {
  return Promise.reject(error)
})

export default http
